<?php
/**
 * @file   admin.php
 * @date   2017-11-15 15:22:57
 * @author huwhis<huuwhois>
 * @version   0.0.1
 */

namespace app\admin\controller;

use app\admin\model\Adminuser as AdminuserModel;
use think\Request;

class Adminuser extends Base
{
    protected $adminuser_model;
    protected $adminuser_info;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->adminuser_model = new AdminuserModel();
        $this->adminuser_info = $this->adminuser_model->field(true)->find($this->user_id);
    }

//我的信息
    public function index()
    {
        return $this->listing();
    }

//管理员列表List    
    public function listing()
    {
        $page_counts = config('paginate.list_rows');//config('paginate.list_rows'),tp5配置的每页行数;可自定义$page_counts =20;
        $counts = $this->adminuser_model->count('id');
        $pages = intval(ceil($counts/$page_counts));
        $data = $this->adminuser_model->field('id,admin_name,role_id,pen_name,email,ctime,ltime,loginip,isban')->paginate($page_counts, $counts);
        // var_dump($data);exit;
        $this->assign("pages", $pages);
        $this->assign("counts", $counts);
        $this->assign("data", $data);
        return $this->fetch('listing');
    }

//添加管理员
    public function add()
    {
        if (Request::instance()->isPOST()) {
            // var_dump(input('post.'));exit;

            if (input('post.adminName')=='' || input('post.password')=='' || input('post.email')=='') {
                $this->error("用户名 or 密码 or 邮箱 不能为空!");
            }

            $this->adminuser_model->admin_name = input('post.adminName');
            $this->adminuser_model->pen_name =  input('post.penName');
            $this->adminuser_model->password = md5(input('post.password'));
            $this->adminuser_model->email = input('post.email');
            $this->adminuser_model->role_id = input('post.adminRole');
            $this->adminuser_model->ctime = time();
            $this->adminuser_model->isban = intval(input('post.isban'));
            $this->adminuser_model->note = input('post.note');
    
            try {
                $this->adminuser_model->save();
            } catch (\Exception $e) {
                $msg = $e->getMessage();
                $msg = substr($msg, 0, 15);
                // echo $msg;exit;
                $this->error("错误代码:".$msg);
            }
                $this->success('添加成功', 'listing');
        } else {
            $rolename = model('adminrole')->adminroleName();
           
            $this->assign("rolename", $rolename);

            return $this->fetch();
        }
    }

//停用管理员
    public function stop($id = '', $isban = 0)
    {
        if (Request::instance()->isAjax()) {
            if ($id == 1) {
                return ['status'=>0,'msg'=>'超级管理员禁止停用'];
            }
            if ($this->adminuser_model->save(['isban' =>1], ['id' => $id])) {
                return ['status'=>1,'msg'=>'停用成功'];
            } else {
                return ['status'=>0,'msg'=>'停用失败'];
            }
        }
    }
//启用用管理员
    public function start($id = '', $isban = 0)
    {
        if (Request::instance()->isAjax()) {
            if ($id == 1) {
                return ['status'=>0,'msg'=>'超级管理员禁止停用'];
            }
            if ($this->adminuser_model->save(['isban' =>0], ['id' => $id])) {
                return ['status'=>1,'msg'=>'启用成功'];
            } else {
                return ['status'=>0,'msg'=>'启用失败'];
            }
        }
    }
    
//look
    public function look($id = '')
    {
        $data = $this->adminuser_model->get($id);
        // var_dump($data);
        $this->assign('data', $data);
        return $this->fetch();
    }

//编辑管理员信息
    public function edit($id)
    {
        $data = $this->adminuser_model->find($id);
        if (Request::instance()->isPOST()) {
            // var_dump(input('post.'));
            // exit;
            
            if (input('post.adminName')=='' || input('post.email')=='') {
                $this->error("用户名 or  邮箱 不能为空!");
            }

            $data->admin_name = input('post.adminName');
            $data->role_id = input('post.adminRole');
            $data->pen_name = input('post.penName');
            $data->email =  input('post.email');
            $data->isban = intval(input('post.isban'));
            $data->note = input('post.note');

            try {
                $data->save();
            } catch (\Exception $e) {
                $msg = $e->getMessage();
                $msg = substr($msg, 0, 15);
                // echo $msg;exit;
                $this->error("错误代码:".$msg);
            }
                $this->success('编辑成功', 'listing');
        } else {
            // var_dump($data);exit;
            $rolename = model('adminrole')->adminroleName();
            // var_dump($typename);exit;

            $this->assign("rolename", $rolename);
            $this->assign('data', $data);
            return $this->fetch();
        }
    }
    
//(批量)删除管理员
    public function del($id = null)
    {
        if (Request::instance()->isAjax()) {
            if (is_array($id)) {
                if (in_array('1', $id)) {
                    return ['status'=>0,'msg'=>'超级管理员无法删除'];
                }
                if (in_array(session('user_id'), $id)) {
                    return ['status'=>0,'msg'=>'当前用户无法删除'];
                }
            } else {
                if ($id == 1) {
                    return ['status'=>0,'msg'=>'超级管理员无法删除'];
                }
                if ($id == session('user_id')) {
                    return ['status'=>0,'msg'=>'当前用户无法删除'];
                }
            }
            if ($this->adminuser_model->destroy($id)) {
                return ['status'=>1,'msg'=>'删除成功'];
            } else {
                return ['status'=>0,'msg'=>'删除失败'];
            }
        }
    }

    
/**个人中心
 * 邮箱 modifyEmail
 * 密码 modifyPwd
 * 头像
 *
*/
//个人信息
    public function myinfo()
    {
        $lgdata = \think\Db::query("select lgtime,lgip,browser from dean_login_note where userid='".$this->user_id."'");

        $this->assign('lgdata', $lgdata);
        $this->assign('data', $this->adminuser_info);
        return $this->fetch();
    }

//修改邮箱
    public function modifyEmail()
    {
        $step =  intval(input("post.step"));
        $useremail = $this->adminuser_info->email;
    //ajax验证邮箱
        if (Request::instance()->isAjax()) {
            $email = trim(input('post.email'));
            $all_email = $this->adminuser_model->column('email');
            if (in_array($email, $all_email)) {
                return ['status'=>0,'msg'=>'此邮箱已被使用'];
            } else {
                return ['status'=>1,'msg'=>"此邮箱可用"];
            }
        } elseif (Request::instance()->isPOST()) {
            if ($step==1) {
                $email = trim(input('post.email'));
                $token = mt_rand(100000, 999999); // 6位数验证码
                $emailbody = "亲爱的".$this->user_name."：<br/>您正在启用新邮箱。<br/>验证码:<b>$token</b>请在操作页面输入此验证码完成邮箱验证。<br/>验证密码4小时内有效。<br/><br/><br/><p style='text-align:left'>-------- huwhois敬上</p>";
            
                $result = send_email($email, '绑定邮箱', $emailbody);
                if ($result==1) {
                    session('token', $token);
                    session('newemail', $email);
                    $this->success('验证码发送成功请注意查收');
                } else {
                    $this->error('验证码获取失败');
                }
            }
            if ($step==2) {
                $token = input('post.token');
                if (session('?token') && session('token')==$token) {
                    $email = session('newemail');
                    $this->adminuser_info->email = $email;
                    if ($this->adminuser_info->save()) {
                        session('token', null);
                        session('tokenok', 1);
                        $this->success('邮箱保存成功');
                    } else {
                        $this->error('邮箱保存失败，请稍后重试');
                    }
                } else {
                    $this->error('验证码不正确');
                }
            }
        } else {
            if (session('?token')) {
                $this->assign('step', 2);
                return $this->fetch();
            } elseif (session('?tokenok') && session('tokenok')==1) {
                $newemail = session('newemail');
                session('tokenok', null);
                $this->assign('newemail', $newemail);
                $this->assign('step', 3);
                return $this->fetch();
            } else {
                $this->assign('step', 1);
                return $this->fetch();
            }
        }
    }
//修改密码
    public function modifyPwd()
    {
        $pwd = $this->adminuser_info->password;
    //ajax验证密码
        if (Request::instance()->isAjax()) {
            $password = md5(trim(input('post.password')));
            if ($pwd==$password) {
                return ['status'=>1];
            } else {
                return ['status'=>0];
            }
        } elseif (Request::instance()->isPOST()) {
            $oldpwd = md5(trim(input('post.oldpassword')));
            $newpwd = md5(trim(input('post.newpassword')));
            $repwd = md5(trim(input('post.repassword')));
            if ($pwd!=$oldpwd) {
                $this->error('原密码不正确');
            }
            if ($newpwd!=$repwd) {
                $this->error('两次新密码不一致，请核查');
            }
            $this->adminuser_info->password = $newpwd;
            if ($this->adminuser_info->save()) {
                session(null);
                $this->success("修改成功,请重新登陆", 'login/logout');
            } else {
                $this->error('修改失败，请稍后重试');
            }
        } else {
            return $this->fetch();
        }
    }
}
